package com.epfresh.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.activity.OfferMyActivity;
import com.epfresh.activity.SearchActivity;
import com.epfresh.activity.SelectNameEnsureActivity;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.widget.tablayout.SlidingTabLayout;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;
import com.epfresh.basedialog.CustomDialog;
import com.epfresh.bean.Category;
import com.epfresh.bean.Market;
import com.epfresh.bean.ProductCategory;
import com.epfresh.delegate.CategoryGoodsDelegate;
import com.epfresh.delegate.CategoryGoodsMarketFilterDelegate;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseFragment;
import com.epfresh.global.DataManager;
import com.epfresh.views.MultiStateView;
import com.epfresh.views.dialog.BaseDialogView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author wangzhanghuan
 * @version 1.0
 * @date create 17-3-23
 * @Description
 */
public class CategoryGoodsFragment extends BaseFragment implements OnTabSelectListener {

    public CategoryGoodsDelegate cgDelegate;
    CategoryGoodsMarketFilterDelegate cgmDelegate;
    private View vSearch;
    private View vMy;
    private TextView tvMarket;
    private ImageView ivMarket;


    private SlidingTabLayout lyTab;
    private List<Category> listCategory = new ArrayList<>();
    List<Market> listMarket = new ArrayList<>();

    MultiStateView multiStateView;

    @Override
    public String getBaseTag() {
        return "categoryGoodsFragment";
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        return inflater.inflate(R.layout.fragment_category_goods,
                container, false);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        FragmentActivity activity = getActivity();

//        cgDelegate = new CategoryGoodsDelegate((BaseActivity) activity,this, view);

        multiStateView = (MultiStateView) view.findViewById(R.id.cg_mult_state_view);
        multiStateView.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        multiStateView.setViewForState(R.layout.empty_goods, MultiStateView.VIEW_STATE_EMPTY);
        multiStateView.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_ERROR);
        multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);

        multiStateView.setOnErrorClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listMarket.size() > 0)
                    requestCategory(null);
            }
        });
        multiStateView.setOnEmptyClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateData(false);
            }
        });

        lyTab = (SlidingTabLayout) view.findViewById(R.id.ly_navigation);
        lyTab.setOnTabSelectListener(this);
        vSearch = view.findViewById(R.id.tv_search);
        vMy = view.findViewById(R.id.tv_my);
        tvMarket = (TextView) view.findViewById(R.id.tv_market);
        tvMarket.setOnClickListener(this);
        ivMarket = (ImageView) view.findViewById(R.id.iv_market);
        ivMarket.setOnClickListener(this);
        vSearch.setOnClickListener(this);
        vMy.setOnClickListener(this);
        updateDataNew();

    }


    public void updateMarket() {

        listMarket.clear();

        listMarket.addAll(DataManager.getInstance().list);
        tvMarket.setText("全部");

    }

    private void updateCategoryTitle(String[] titles) {
        lyTab.setTitles(titles);
    }

    private String[] getCategoryFirst() {
        if (listCategory.size() > 0) {
            String[] strings = new String[listCategory.size()];
            for (int i = 0; i < listCategory.size(); i++) {
                Category category = listCategory.get(i);
                strings[i] = category.getName();
            }
            return strings;
        }
        return new String[0];
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.tv_search:
                Intent search = new Intent(getActivity(), SearchActivity.class);
                startActivity(search);
                break;
            case R.id.tv_my:
/*                Log.e("getCertStatus",""+getUser().getCertStatus());
                if(getUser().getCertStatus()==0||getUser().getCertStatus()==3) {
                    showNameSure();
                    return;
                }*/
                Intent ask = new Intent(getContext(), OfferMyActivity.class);
                startActivityForResult(ask,0x0404);
                break;
            case R.id.tv_market:
            case R.id.iv_market:
                openMarket();
                break;
        }
    }

    CustomDialog.Builder builder;

    public void showNameSure() {
        if (builder == null)
            builder = new CustomDialog.Builder(getAppActivity());
        builder.setMessage("\n还剩一步\n去完善实名认证，向批发商问价\n");//设置显示的内容
        //builder.setTitle("还剩一步");
        builder.setPositiveButton("去认证", new DialogInterface.OnClickListener() {//添加确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                Intent ensure = new Intent(getActivity(), SelectNameEnsureActivity.class);
                ensure.putExtra("home_tab_index",1);
                startActivity(ensure);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("放弃", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });
        builder.create().show();
        return;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("________", "requestCode" + "" + requestCode);
        if (resultCode == 0x0404) {//去问价>>全部商品
            cgDelegate.refresh(false);
            return;
        }
    }



    Set<Integer> currentSet;
    List<String> marketIds;

//    private void updateFilterArrow() {
////
//    }

    private void openMarket() {

        if (getActivity() == null) {
            return;
        }
        if (cgmDelegate == null) {
            cgmDelegate = new CategoryGoodsMarketFilterDelegate((BaseActivity) getActivity());

            cgmDelegate.setOnFilter(new CategoryGoodsMarketFilterDelegate.OnFilter() {
                @Override
                public void onFilter(Set<Integer> set, List<String> ids, String name) {

                    currentSet = set;
                    marketIds = ids;
                    mMarketIds = ids;
                    mCategoryId = null;
                    mNameId = null;
                    mTopCategoryId = null;
                    tvMarket.setText(name);
                    if (ids != null && ids.size() == 1) {
                        String s = ids.get(0);
                        if (s == null || "".equals(s) || "0".equals(s)) {
                            requestCategory(null);

                            return;
                        }
                    }

                    if (ids != null && ids.size() == 0) {
                        requestCategory(null);

                        return;
                    }


                    requestCategory(ids);
//                cgDelegate.updateList();
                }
            });

            cgmDelegate.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    ivMarket.setImageResource(R.mipmap.home_all_down);
                }
            });
        }
        if (cgmDelegate.isShowing()) {
            ivMarket.setImageResource(R.mipmap.home_all_down);
            cgmDelegate.dismiss();
        } else {


            if (listMarket.size() > 0) {
                ivMarket.setImageResource(R.mipmap.home_all_up);
                cgmDelegate.show(listMarket, currentSet);
            }
        }
//        updateFilterArrow();

    }

    public boolean isCategoryDialogShow() {
        return cgmDelegate != null && cgmDelegate.isShowing();
    }

    public void dismissCategoryDialog() {
        if (cgmDelegate != null) {
            ivMarket.setImageResource(R.mipmap.home_all_down);
            cgmDelegate.dismiss();
        }
    }

    public void updateData(boolean isproduct) {
       /* if (currentSet != null) {
            currentSet.clear();
        }
        updateMarket();
        if (listMarket.size() == 0) {//没有批发市场
            multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        } else {
            requestCategory(null);
        }*/
        if (!isproduct) {
            mTopCategoryId = null;
            mCategoryId = null;
            mNameId = null;
            marketIds = null;
        }
        updateDataNew();

    }


    List<String> mMarketIds;
    String mTopCategoryId;
    String mCategoryId;
    String mNameId;


    public void updateStatus(List<String> marketIds,String topCategoryId,String categoryId,String nameId) {

        mMarketIds = marketIds;
        mTopCategoryId = topCategoryId;
        mCategoryId = categoryId;
        mNameId = nameId;
        this.marketIds = marketIds;
    }

    public void updateDataNew() {


        if (currentSet != null) {
            currentSet.clear();
        }
        updateMarket();
        int size = listMarket.size();
        Log.e("market","listMarket:"+size);

        String marketName = "全部";
        if (marketIds != null && marketIds.size() > 0 && size > 0){
            String s = marketIds.get(0);
            for (int i = 0;i< size;i++){
                Market market = listMarket.get(i);
                String id = market.getId();
                if (id != null && !"".equals(id)&& id.equals(s)){
                    if (currentSet == null){
                        currentSet = new HashSet<>();
                    }
                    marketName = market.getShortName();
                    currentSet.add(i+1);
                    break;
                }
            }
        }
        tvMarket.setText(marketName);
        if (size == 0) {//没有批发市场
            multiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
        } else {
            requestCategory(marketIds);
        }


    }


    public void requestCategory(List<String> markets) {
        if (markets == null) {
            marketIds = null;
        }
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_category_tree4purchaser);

        re.putParameter("marketIds", markets);
        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_category_tree4purchaser, onRequestListener);
    }

    private OnRequestListener<List<Category>> onRequestListener = new OnRequestListener<List<Category>>() {
        @Override
        public List<Category> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<List<Category>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
        }

        @Override
        public void onStart(Object o) {
            multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        }

        @Override
        public void onResponse(ResponseEntity<List<Category>> responseEntity, Object o) {
            multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);

            List<Category> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                listCategory.clear();
                listCategory.addAll(responseElement);
                updateCategoryStatus();

            }


        }
    };

    void updateCategoryStatus(){
        int index = 0;
        String[] categoryFirst ;

        if (listCategory.size() > 0) {
            String[] strings = new String[listCategory.size()];
            for (int i = 0; i < listCategory.size(); i++) {
                Category category = listCategory.get(i);
                strings[i] = category.getName();
                String id = category.getId();
                if (id != null && !"".equals(id) && id.equals(mTopCategoryId)){
                    index = i;
                }
            }
            categoryFirst =  strings;
        }else {
            categoryFirst = new String[0];
        }



        updateCategoryTitle(categoryFirst);

        updateListStatus(index);
        lyTab.setCurrentTab(index);
        lyTab.smoothScrollTo(0,0);
    }


    @Override
    public void onTabSelect(int i) {
        mNameId = null;
        updateListStatus(i);
    }

    private void updateListStatus(int i) {
        if (cgDelegate != null) {
            cgDelegate.dismissFilter();
        }
        if (i < listCategory.size()) {
            Category category = listCategory.get(i);
            List<ProductCategory> categories = category.getCategories();
            if (categories != null && categories.size() > 0) {
                for (int j = 0; j < categories.size(); j++) {
                    ProductCategory productCategory = categories.get(j);
                    productCategory.setSelect(false);
                }
                ProductCategory productCategory = categories.get(0);
                productCategory.setSelect(true);
            }
            List<String > list = null;
            if (mNameId != null){
               list = new ArrayList<>();
               list.add(mNameId);
            }
            cgDelegate.updateList(category.getId(), categories,mCategoryId,list, marketIds);
        }
    }

    @Override
    public void onTabReselect(int i) {

    }


    public void updateCount() {
        if (getActivity() != null && cgDelegate != null) {
            cgDelegate.requestCount();
        }
    }



}
